package com.bitcat.todoapp.demo

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.todoapp.R
import kotlin.concurrent.thread

class ThreadDemoActivity : AppCompatActivity() {

    private val handler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_thread_demo)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    fun method1(view: View) {
        Thread.sleep(10000)
        Toast.makeText(this, "method1被点击了", Toast.LENGTH_SHORT).show()
    }
    fun method2(view: View) {
        Toast.makeText(this, "method2被点击了", Toast.LENGTH_SHORT).show()
    }

    fun method3(view: View) {

//        val btn = view as Button
//        btn.text = "按钮4"
        thread {
            val btn = view as Button
            btn.text = "按钮4" // 子线程中不能修改UI
        }
    }

    //演示Activity.runOnUiThread(Runnable)
    fun method4(view: View) {
        thread {
            val btn = view as Button
            runOnUiThread {
                //已经是主线程
                btn.text = "hello world"
            }

        }
    }

    //View.post(Runnable) / View.postDelayed()
    fun method5(view: View) {
        thread {
            val btn = view as Button
//            view.post {
//                btn.text = "hello world"
//            }

            view.postDelayed({ //主线程
                btn.text = "hello world"
            },2000)

        }
    }

    fun method6(view: View) {
        thread {
            val btn = view as Button
            handler.post { btn.text = "hello world" }
        }
    }
}